#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <linux/tls.h>
#include <netinet/tcp.h>
#include <sys/socket.h>

#define SERVER_IP "127.0.0.1" // 替换为服务器IP地址
#define PORT 12345
#define BUFFER_SIZE 1024
#define TLS_KEY_SIZE 16
#define TLS_IV_SIZE 12
#define TLS_REC_SEQ_SIZE 8

void hexdump(const void *data, size_t size) {
    const unsigned char *byte = data;
    for (size_t i = 0; i < size; i++) {
        printf("%02x ", byte[i]);
        if ((i + 1) % 16 == 0) {
            printf("\n");
        }
    }
    printf("\n");
}

int main() {
    int sockfd;
    struct sockaddr_in server_addr;
    struct tls12_crypto_info_aes_gcm_128 crypto_info;
    memset(&crypto_info, 0, sizeof(crypto_info));

    // 创建套接字
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    // 配置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
        perror("inet_pton");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    // 连接到服务器
    if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("connect");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    printf("Connected to server\n");

    // 设置 kTLS 加密信息
    crypto_info.info.version = TLS_1_2_VERSION;
    crypto_info.info.cipher_type = TLS_CIPHER_AES_GCM_128;

    // 初始化 key 和 iv 为示例值，你应该替换为实际的值
    unsigned char key[TLS_KEY_SIZE] = { 0x00 };
    unsigned char iv[TLS_IV_SIZE] = { 0x00 };
    unsigned char rec_seq[TLS_REC_SEQ_SIZE] = { 0x00 };

    memcpy(crypto_info.key, key, sizeof(crypto_info.key));
    memcpy(crypto_info.iv, iv, sizeof(crypto_info.iv));
    memcpy(crypto_info.rec_seq, rec_seq, sizeof(crypto_info.rec_seq));

    // 启用 kTLS
    if (setsockopt(sockfd, SOL_TCP, TCP_ULP, "tls", sizeof("tls")) < 0) {
        perror("setsockopt TCP_ULP");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    if (setsockopt(sockfd, SOL_TLS, TLS_TX, &crypto_info, sizeof(crypto_info)) < 0) {
        perror("setsockopt TLS_TX");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    if (setsockopt(sockfd, SOL_TLS, TLS_RX, &crypto_info, sizeof(crypto_info)) < 0) {
        perror("setsockopt TLS_RX");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    printf("kTLS enabled for connection to server\n");

    // 发送和接收数据
    char buffer[BUFFER_SIZE] = "Hello, kTLS server!";
    if (send(sockfd, buffer, strlen(buffer), 0) < 0) {
        perror("send");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    ssize_t len;
    if ((len = recv(sockfd, buffer, sizeof(buffer), 0)) < 0) {
        perror("recv");
    } else {
        printf("Received (%zd bytes):\n", len);
        hexdump(buffer, len);
    }

    close(sockfd);
    return 0;
}

